#include "register.h"
#include "ui_register.h"

Register::Register(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
}

Register::~Register()
{
    delete ui;
}

void Register::on_pushButton_clicked()
{
    emit TomainSignal();
}

//注册
void Register::on_pushButton_2_clicked()
{
    connectDB();
    QString name = ui->lineEdit->text();
    QString phone = ui->lineEdit_2->text();
    QString account = ui->lineEdit_3->text();
    QString pwd = ui->lineEdit_4->text();
    QSqlQuery query;
    QString insertuser="INSERT INTO user (name,phone,account,pwd) VALUES ('"+name+"', '"+phone+"','"+account+"','"+pwd+"');";
            if(!query.exec(insertuser))
            {
                qDebug()<<"query error :"<<query.lastError();
            }
            else{
                    qDebug()<<"添加成功!";
                }
     db.close();
     ui->lineEdit->clear();
     ui->lineEdit_2->clear();
     ui->lineEdit_3->clear();
     ui->lineEdit_4->clear();


}

//连接数据库
void Register::connectDB()
{
    //连接数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    if(QSqlDatabase::contains("qt_sql_default_connection"))
    {
      db = QSqlDatabase::database("qt_sql_default_connection");
    }
    else
    {
      db = QSqlDatabase::addDatabase("QSQLITE");
    }
    db.setDatabaseName("testDB.db");//数据库名称
    db.setUserName("root");//用户名
    db.setPassword("123456");//密码
    bool ok = db.open();
    if(ok)
    {
        QMessageBox::information(this, "提示","数据库连接成功");
        qDebug()<<"数据库连接成功";
    }
    else
    {
        QMessageBox::information(this, "提示","数据库连接失败");
        this->close();
        qDebug()<<"数据库连接失败";
    }

    //若数据库中没有表，则新建
    QSqlQuery query;
    QString createTableUser="CREATE TABLE user \
            (                                  \
              name      TEXT NOT NULL ,\
              phone     TEXT NOT NULL ,\
              account   TEXT NOT NULL ,\
              pwd       TEXT NOT NULL  \
            )";
            query.exec(createTableUser);
}

